import java.util.ArrayList;
import java.util.List;

public class Solution140 {

    public static class Trie{
        boolean end;
        Trie[] tries=new Trie[26];

        void insert(String t){
            Trie node=this;
            for (char c : t.toCharArray()) {
                if (node.tries[c-'a']==null){
                    node.tries[c-'a']=new Trie();
                }
                node=node.tries[c-'a'];
            }
            node.end=true;
        }

        List<Integer> search(String t){
            Trie node=this;
            List<Integer> list=new ArrayList<>();
            for (int i=0;i<t.length();i++){
                if (node.tries[t.charAt(i)-'a']==null){
                    return list;
                }
                node=node.tries[t.charAt(i)-'a'];
                if (node.end){
                    list.add(i);
                }
            }
            return list;
        }
    }

    public List<String> wordBreak(String s, List<String> wordDict) {
        Trie trie=new Trie();
        for (String s1 : wordDict) {
            trie.insert(s1);
        }
        List<String> ans=new ArrayList<>();
        List<String> temp=new ArrayList<>();
        dfs(0,s,ans,temp,trie);
        return ans;
    }

    void dfs(int cur,String s,List<String> ans,List<String> temp,Trie trie){
        if (cur==s.length()){
            ans.add(deal(temp));
            return;
        }
        List<Integer> list=trie.search(s.substring(cur));
        for (Integer integer : list) {
            temp.add(s.substring(cur,cur+integer+1));
            dfs(cur+integer+1,s,ans,temp,trie);
            temp.remove(temp.size()-1);
        }
    }

    String deal(List<String> list){
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(list.get(0));
        for (int i=1;i<list.size();i++){
            stringBuilder.append(' ').append(list.get(i));
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        List<String> list=new ArrayList<>();
        list.add("cat");
        list.add("cats");
        list.add("and");
        list.add("sand");
        list.add("dog");
        System.out.println(new Solution140().wordBreak("catsanddog",list));
    }
}
